package handler

import (
	"encoding/base64"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/juexin/gin-base/internal/service"
	"github.com/juexin/gin-base/pkg/response"
)

type CaptchaHandler struct {
	captchaService *service.CaptchaService
}

func NewCaptchaHandler(captchaService *service.CaptchaService) *CaptchaHandler {
	return &CaptchaHandler{
		captchaService: captchaService,
	}
}

// GenerateCaptcha 生成图形验证码
func (h *CaptchaHandler) GenerateCaptcha(c *gin.Context) {
	result, err := h.captchaService.GenerateCaptcha()
	if err != nil {
		response.Error(c, http.StatusInternalServerError, "生成验证码失败: "+err.Error())
		return
	}

	// 将图片数据转换为base64
	imageBase64 := base64.StdEncoding.EncodeToString(result.Image)

	response.SuccessWithMsg(c, "生成验证码成功", map[string]interface{}{
		"captcha_id": result.CaptchaID,
		"image":      "data:image/jpeg;base64," + imageBase64,
	})
}

// VerifyCaptcha 验证图形验证码
func (h *CaptchaHandler) VerifyCaptcha(c *gin.Context) {
	var req service.CaptchaVerifyRequest

	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, "参数错误: "+err.Error())
		return
	}

	err := h.captchaService.VerifyCaptcha(&req)
	if err != nil {
		response.Error(c, http.StatusBadRequest, "验证失败: "+err.Error())
		return
	}

	response.SuccessWithMsg(c, "验证成功", nil)
}
